#include "appinc.h"
#include "sans_demo.h"


const char *props_demo = TOSTR(
{
	"basic":{
		"model": "product_demo",
		"sn": "sn_demo123"
	}, 
	"modem": {
		"imei": "861241054843071",
		"csq": 23,
		"ip": "10.20.145.131"
	}
}
);


static int sans_props_get(void *obj, ssiot_message_t *msg, cJSON *data)
{
	char *path = "";

	if (msg->to) {
		//当前设备不支持查询下位机props
		msg->resp_code = SSCODE_ERR_REQUEST;
		msg->resp_msg = "not support subdevice";
		return 0;
	}

	if (data && data->type == cJSON_Object) {
		data = cJSON_GetObjectItem(data, "path");
		if (data && data->valuestring)
			path = data->valuestring;
	}

	//toto create prop json data
	data = cJSON_Parse(props_demo);
	if (data == NULL)
		return -ENOMEM;
	if (*path != '\0')
		json_retian(data, path);
	if (data->child == NULL)
		data->type = cJSON_NULL;

	msg->resp_code = SSCODE_OK;
	msg->resp_data = data;

	return 0;
}


static int sans_props_set(void *obj, ssiot_message_t *msg, cJSON *data)
{
	//当前设备不支持设置任何props
	msg->resp_code = SSCODE_ERR_REQUEST;
	msg->resp_msg = "not support";

	return 0;
}


int sans_props(void *obj, const char *topic, ssiot_message_t *msg)
{
	if (!strcmp(topic, "get"))
		return sans_props_get(obj, msg, msg->data);
	else if (!strcmp(topic, "set"))
		return sans_props_set(obj, msg, msg->data);
	
	return -EINVAL;
}


int props_demo_send(void)
{
	static int first = 1;
	cJSON *data;

	data = cJSON_Parse(props_demo);
	//首次上报所有，后续只上报随机csq
	if (first == 0) {
		cJSON *csq = json_sub(data, "modem.csq", false);
		if (csq) {
			uint32_t val = 10 + rand()%20;
			csq->valueint = val;
			csq->valuedouble = (double)val;
		}
		json_retian(data, "modem.csq");
	}
	
	ssiot_send_data(NULL, NULL, -1, "props", data);
	cJSON_Delete(data);
	first = 0;

	return 0;
}

